package com.wsq.tif;

import java.awt.image.RenderedImage;
import java.awt.image.renderable.ParameterBlock;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import javax.media.jai.JAI;
import javax.media.jai.RenderedOp;

import com.sun.media.jai.codec.FileSeekableStream;
import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.JPEGEncodeParam;
import com.sun.media.jai.codec.TIFFDecodeParam;
import com.sun.media.jai.codec.TIFFEncodeParam;
import com.sun.media.jai.codecimpl.JPEGCodec;
import com.sun.media.jai.codecimpl.JPEGImageDecoder;

public class Tif2pdfRunnable implements Runnable {
	private int pageIndex;
	private CountDownLatch countDownLatch;
	private String filePath;

	public Tif2pdfRunnable(int pageIndex, CountDownLatch cyclicBarrier,
			String filePath) {
		super();
		this.pageIndex = pageIndex;
		this.countDownLatch = cyclicBarrier;
		this.filePath = filePath;
	}

	@Override
	public void run() {
		FileSeekableStream ss = null;
		try {
			ss = new FileSeekableStream(filePath);
			TIFFDecodeParam param0 = null;
			TIFFEncodeParam param = new TIFFEncodeParam();
			JPEGEncodeParam param1 = new JPEGEncodeParam();
			param1.setQuality((float) 0.3);
			ImageDecoder dec = ImageCodec
					.createImageDecoder("tiff", ss, param0);
			int count = dec.getNumPages();
			param.setCompression(TIFFEncodeParam.COMPRESSION_JPEG_TTN2);
			param.setLittleEndian(false); // Intel
			param.setJPEGEncodeParam(param1);
			System.out.println("This TIF has " + count + " image(s)");
			RenderedImage page = dec.decodeAsRenderedImage(pageIndex);
			File f = new File("d:/tif/page_" + (pageIndex + 1) + ".jpg");
			System.out.println("Saving " + f.getCanonicalPath());
			ParameterBlock pb = new ParameterBlock();
			pb.addSource(page);
			pb.add(f.toString());
			pb.add("JPEG");
			pb.add(param1);
			RenderedOp r = JAI.create("filestore", pb);
			r.dispose();
			System.out.println(pageIndex);
			countDownLatch.countDown();
		} catch (IOException e) {
			e.printStackTrace();
		}/*
		 * finally{ try { ss.close(); } catch (IOException e) {
		 * e.printStackTrace(); } }
		 */
	}

}
